<?php
/**
 * Houses Model for Congregation Component
 * 
 * @package    Congregation
 * @subpackage Components
 * @link http://docs.joomla.org/Developing_a_Model-View-Controller_Component_-_Part_4
 * @license		GNU/GPL
 */

// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport('joomla.application.component.model');

/**
 * Sharing Sharing Model
 *
 * @package    Joomla.Tutorials
 * @subpackage Components
 */
class CongregationModelHouses extends CongregationModel
{

	var $_data;


  /**
   * Returns the query for listing the categories
   *
   * @access  protected
   * @return  string    The query to be used to retrieve the categories data from the database
   * @since   1.5.5
   */
  function _buildQuery()
  {
	
	
	$query = "SELECT c.*, p.p_id, p.p_name, count(t.t_username) AS members 
		FROM #__congregation_casa AS c 
		LEFT JOIN #__congregation_profile_paths AS t
			on (c.c_id=t.t_cid AND t.t_current = 1)
		LEFT JOIN #__congregation_province AS p
			on c.p_id=p.p_id
		GROUP BY c.c_id " .
		$this->_buildWhere() . 
		$this->_buildOrderby();
			
	echo $query;

    return $query;
  }


	function _buildWhere()
	{
		$where = array();
		$p_id	= JRequest::getInt('p_id'); 
		if($p_id)
		{
			$where[] = 'c.p_id = ' . $p_id; 
		}
		
		$where = count($where) ? ' HAVING ' . implode(' AND ', $where) : '';

		return $where;
	}
	
	function _buildOrderby()
	{
		$ordering = JRequest::getVar('ordering');

		$sortorder  = '';
		if(!$ordering)
		{
		  $sortorder = ' p.ordering, p.p_id, c.ordering, c.c_name';
		}
		else
		{
		  $sortorder = $ordering;
		}

		if ($sortorder != ''){
		  $orderby = ' ORDER BY '.$sortorder;
		}

		return $orderby;

	}
  
	/**
	* Method to get province list according to params
	*
	*/

	
	function getData()
	{
		// Lets load the data if it doesn't already exist
		if (empty( $this->_data ))
		{
			
			$query = $this->_buildQuery();
			
			$this->_db->setQuery( $query );
			
			$this->_data = $this->_getList( $query );
			
		}

		return $this->_data;
	
	}
	
		/**
		* Method to get the total number of houses
		*
		* @access  public
		* @return  int     The total number of categories
		* @since   1.5.5
		*/
		function getTotal()
		{
		// Let's load the number of categories if it doesn't already exist
		if (empty($this->_total))
		{
			$query = $this->_buildQuery();
		  
			$this->_total = $this->_getListCount($query);
			
		}

		return $this->_total;
		}


}